/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dieci.ui;

import dieci.managers.rawmaterial.RawMaterialManager;
import dieci.managers.rawmaterial.RawMaterialProductManager;
import dieci.managers.stockmanager.ProductManager;
import dieci.system.OrderDetails;
import dieci.system.Product;
import dieci.system.RawMaterial;
import dieci.system.RawMaterialProduct;
import static java.awt.Frame.MAXIMIZED_BOTH;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Pc
 */
public class RawMaterialProductsUI extends javax.swing.JFrame
{

    private ProductManager productManager;
    private RawMaterialProductManager rawMaterialProductManager;
    private RawMaterialManager rawMaterialManager;
    private Product selectedProduct;
    
    /**
     * Creates new form WindowRawMaterialProducts
     */
    public RawMaterialProductsUI()
    {
        productManager = new ProductManager();
        rawMaterialManager = new RawMaterialManager();
        rawMaterialProductManager = new RawMaterialProductManager();
                
        initComponents();
        
        getAllProductsFromDB();
        
        ImageIcon imageIcon = new javax.swing.ImageIcon(getClass().getResource("/dieci/ui/icon_image.jpg"));
        this.setIconImage(imageIcon.getImage());
        this.setExtendedState(MAXIMIZED_BOTH);
        this.setVisible(true);
        this.jPanelMateriaPrimaProd.setVisible(false);
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        North = new javax.swing.JPanel();
        East = new javax.swing.JPanel();
        Center = new javax.swing.JPanel();
        jPanelMateriaPrimaProd = new javax.swing.JPanel();
        jScrollPane7 = new javax.swing.JScrollPane();
        jTableMatPrimaProducto = new javax.swing.JTable();
        jLabel42 = new javax.swing.JLabel();
        jTextFieldBuscarMatPrima = new javax.swing.JTextField();
        jButtonBuscarMatPrima = new javax.swing.JButton();
        jScrollPane6 = new javax.swing.JScrollPane();
        jListMateriaPrima = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldCostoFinal = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jButtonEditMatPrimaProd = new javax.swing.JButton();
        jButtonGuardarMatPrimaProd = new javax.swing.JButton();
        jButtonEliminarMatPrimaProd = new javax.swing.JButton();
        jButtonCancelarMatPrimaProd = new javax.swing.JButton();
        jButtonCalcularCosto = new javax.swing.JButton();
        jButtonEliminarMatPrimaProducto = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabelDetalleProducto = new javax.swing.JLabel();
        jImagenFondo = new javax.swing.JLabel();
        South = new javax.swing.JPanel();
        West = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanelProducts = new javax.swing.JPanel();
        jScrollPaneProducts = new javax.swing.JScrollPane();
        jTableProducts = new javax.swing.JTable();

        setTitle("Materia Prima Productos");

        North.setBackground(new java.awt.Color(241, 245, 255));
        North.setPreferredSize(new java.awt.Dimension(1075, 40));

        javax.swing.GroupLayout NorthLayout = new javax.swing.GroupLayout(North);
        North.setLayout(NorthLayout);
        NorthLayout.setHorizontalGroup(
            NorthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 2140, Short.MAX_VALUE)
        );
        NorthLayout.setVerticalGroup(
            NorthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 40, Short.MAX_VALUE)
        );

        getContentPane().add(North, java.awt.BorderLayout.NORTH);

        East.setBackground(new java.awt.Color(241, 245, 255));
        East.setPreferredSize(new java.awt.Dimension(30, 541));

        javax.swing.GroupLayout EastLayout = new javax.swing.GroupLayout(East);
        East.setLayout(EastLayout);
        EastLayout.setHorizontalGroup(
            EastLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 30, Short.MAX_VALUE)
        );
        EastLayout.setVerticalGroup(
            EastLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 588, Short.MAX_VALUE)
        );

        getContentPane().add(East, java.awt.BorderLayout.EAST);

        Center.setBackground(new java.awt.Color(241, 245, 255));
        Center.setLayout(null);

        jPanelMateriaPrimaProd.setBackground(new java.awt.Color(255, 255, 255));
        jPanelMateriaPrimaProd.setBorder(javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, new java.awt.Color(0, 0, 0)));

        jTableMatPrimaProducto.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][]
            {
                {},
                {},
                {},
                {}
            },
            new String []
            {

            }
        ));
        jTableMatPrimaProducto.setEnabled(false);
        jTableMatPrimaProducto.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                jTableMatPrimaProductoMouseClicked(evt);
            }
        });
        jScrollPane7.setViewportView(jTableMatPrimaProducto);

        jLabel42.setText("Materia Prima:");

        jTextFieldBuscarMatPrima.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jTextFieldBuscarMatPrimaActionPerformed(evt);
            }
        });

        jButtonBuscarMatPrima.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dieci/ui/find_1.jpg"))); // NOI18N
        jButtonBuscarMatPrima.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonBuscarMatPrimaActionPerformed(evt);
            }
        });
        jButtonBuscarMatPrima.addKeyListener(new java.awt.event.KeyAdapter()
        {
            public void keyPressed(java.awt.event.KeyEvent evt)
            {
                jButtonBuscarMatPrimaKeyPressed(evt);
            }
        });

        jListMateriaPrima.setEnabled(false);
        jListMateriaPrima.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                jListMateriaPrimaMouseClicked(evt);
            }
        });
        jScrollPane6.setViewportView(jListMateriaPrima);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel2.setText("->");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setText("$");

        jButtonEditMatPrimaProd.setBackground(new java.awt.Color(0, 153, 204));
        jButtonEditMatPrimaProd.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButtonEditMatPrimaProd.setForeground(new java.awt.Color(255, 255, 255));
        jButtonEditMatPrimaProd.setText("Editar");
        jButtonEditMatPrimaProd.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonEditMatPrimaProdActionPerformed(evt);
            }
        });

        jButtonGuardarMatPrimaProd.setBackground(new java.awt.Color(0, 153, 204));
        jButtonGuardarMatPrimaProd.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButtonGuardarMatPrimaProd.setForeground(new java.awt.Color(255, 255, 255));
        jButtonGuardarMatPrimaProd.setText("Guardar");
        jButtonGuardarMatPrimaProd.setEnabled(false);
        jButtonGuardarMatPrimaProd.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonGuardarMatPrimaProdActionPerformed(evt);
            }
        });

        jButtonEliminarMatPrimaProd.setBackground(new java.awt.Color(0, 153, 204));
        jButtonEliminarMatPrimaProd.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButtonEliminarMatPrimaProd.setForeground(new java.awt.Color(255, 255, 255));
        jButtonEliminarMatPrimaProd.setText("Eliminar");
        jButtonEliminarMatPrimaProd.setEnabled(false);
        jButtonEliminarMatPrimaProd.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonEliminarMatPrimaProdActionPerformed(evt);
            }
        });

        jButtonCancelarMatPrimaProd.setBackground(new java.awt.Color(0, 153, 204));
        jButtonCancelarMatPrimaProd.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButtonCancelarMatPrimaProd.setForeground(new java.awt.Color(255, 255, 255));
        jButtonCancelarMatPrimaProd.setText("Cancelar");
        jButtonCancelarMatPrimaProd.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonCancelarMatPrimaProdActionPerformed(evt);
            }
        });

        jButtonCalcularCosto.setText("Calcular Costo Producto");
        jButtonCalcularCosto.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonCalcularCostoActionPerformed(evt);
            }
        });

        jButtonEliminarMatPrimaProducto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dieci/ui/basurero.jpg"))); // NOI18N
        jButtonEliminarMatPrimaProducto.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonEliminarMatPrimaProductoActionPerformed(evt);
            }
        });
        jButtonEliminarMatPrimaProducto.addKeyListener(new java.awt.event.KeyAdapter()
        {
            public void keyPressed(java.awt.event.KeyEvent evt)
            {
                jButtonEliminarMatPrimaProductoKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanelMateriaPrimaProdLayout = new javax.swing.GroupLayout(jPanelMateriaPrimaProd);
        jPanelMateriaPrimaProd.setLayout(jPanelMateriaPrimaProdLayout);
        jPanelMateriaPrimaProdLayout.setHorizontalGroup(
            jPanelMateriaPrimaProdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelMateriaPrimaProdLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelMateriaPrimaProdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelMateriaPrimaProdLayout.createSequentialGroup()
                        .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 291, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonEliminarMatPrimaProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanelMateriaPrimaProdLayout.createSequentialGroup()
                        .addComponent(jButtonCalcularCosto)
                        .addGap(55, 55, 55)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldCostoFinal, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanelMateriaPrimaProdLayout.createSequentialGroup()
                        .addComponent(jLabel42)
                        .addGap(18, 18, 18)
                        .addComponent(jTextFieldBuscarMatPrima, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonBuscarMatPrima, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(162, 162, 162)
                        .addComponent(jButtonEditMatPrimaProd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonGuardarMatPrimaProd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonEliminarMatPrimaProd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonCancelarMatPrimaProd)))
                .addContainerGap(56, Short.MAX_VALUE))
        );
        jPanelMateriaPrimaProdLayout.setVerticalGroup(
            jPanelMateriaPrimaProdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelMateriaPrimaProdLayout.createSequentialGroup()
                .addGroup(jPanelMateriaPrimaProdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelMateriaPrimaProdLayout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addGroup(jPanelMateriaPrimaProdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanelMateriaPrimaProdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel42)
                                .addComponent(jTextFieldBuscarMatPrima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jButtonBuscarMatPrima, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanelMateriaPrimaProdLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanelMateriaPrimaProdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButtonEditMatPrimaProd)
                            .addComponent(jButtonGuardarMatPrimaProd)
                            .addComponent(jButtonCancelarMatPrimaProd)
                            .addComponent(jButtonEliminarMatPrimaProd))))
                .addGroup(jPanelMateriaPrimaProdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelMateriaPrimaProdLayout.createSequentialGroup()
                        .addGap(133, 133, 133)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanelMateriaPrimaProdLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanelMateriaPrimaProdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButtonEliminarMatPrimaProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanelMateriaPrimaProdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jScrollPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
                                .addComponent(jScrollPane6)))))
                .addGap(39, 39, 39)
                .addGroup(jPanelMateriaPrimaProdLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldCostoFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jButtonCalcularCosto))
                .addContainerGap(66, Short.MAX_VALUE))
        );

        Center.add(jPanelMateriaPrimaProd);
        jPanelMateriaPrimaProd.setBounds(40, 30, 860, 560);

        jLabel1.setText("MATERIA PRIMA PRODUCTO:");
        Center.add(jLabel1);
        jLabel1.setBounds(40, 0, 170, 14);

        jLabelDetalleProducto.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabelDetalleProducto.setText("Seleccione un producto de la lista...");
        Center.add(jLabelDetalleProducto);
        jLabelDetalleProducto.setBounds(220, 0, 590, 15);

        jImagenFondo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dieci/ui/dieci_image.jpg"))); // NOI18N
        jImagenFondo.setPreferredSize(new java.awt.Dimension(20, 20));
        Center.add(jImagenFondo);
        jImagenFondo.setBounds(200, 6, 1590, 670);

        getContentPane().add(Center, java.awt.BorderLayout.CENTER);

        South.setBackground(new java.awt.Color(241, 245, 255));
        South.setPreferredSize(new java.awt.Dimension(1075, 50));

        javax.swing.GroupLayout SouthLayout = new javax.swing.GroupLayout(South);
        South.setLayout(SouthLayout);
        SouthLayout.setHorizontalGroup(
            SouthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 2140, Short.MAX_VALUE)
        );
        SouthLayout.setVerticalGroup(
            SouthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 50, Short.MAX_VALUE)
        );

        getContentPane().add(South, java.awt.BorderLayout.SOUTH);

        West.setBackground(new java.awt.Color(241, 245, 255));
        West.setPreferredSize(new java.awt.Dimension(388, 588));

        jTabbedPane1.setBackground(new java.awt.Color(241, 245, 255));
        jTabbedPane1.addChangeListener(new javax.swing.event.ChangeListener()
        {
            public void stateChanged(javax.swing.event.ChangeEvent evt)
            {
                jTabbedPane1StateChanged(evt);
            }
        });

        jPanelProducts.setBackground(new java.awt.Color(255, 255, 255));

        jTableProducts.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][]
            {

            },
            new String []
            {

            }
        ));
        jTableProducts.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                jTableProductsMouseClicked(evt);
            }
        });
        jTableProducts.addPropertyChangeListener(new java.beans.PropertyChangeListener()
        {
            public void propertyChange(java.beans.PropertyChangeEvent evt)
            {
                jTableProductsPropertyChange(evt);
            }
        });
        jTableProducts.addKeyListener(new java.awt.event.KeyAdapter()
        {
            public void keyPressed(java.awt.event.KeyEvent evt)
            {
                jTableProductsKeyPressed(evt);
            }
        });
        jScrollPaneProducts.setViewportView(jTableProducts);

        javax.swing.GroupLayout jPanelProductsLayout = new javax.swing.GroupLayout(jPanelProducts);
        jPanelProducts.setLayout(jPanelProductsLayout);
        jPanelProductsLayout.setHorizontalGroup(
            jPanelProductsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPaneProducts, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE)
        );
        jPanelProductsLayout.setVerticalGroup(
            jPanelProductsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelProductsLayout.createSequentialGroup()
                .addComponent(jScrollPaneProducts, javax.swing.GroupLayout.PREFERRED_SIZE, 559, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Productos", jPanelProducts);

        javax.swing.GroupLayout WestLayout = new javax.swing.GroupLayout(West);
        West.setLayout(WestLayout);
        WestLayout.setHorizontalGroup(
            WestLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(WestLayout.createSequentialGroup()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 388, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        WestLayout.setVerticalGroup(
            WestLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, WestLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 578, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(65, 65, 65))
        );

        getContentPane().add(West, java.awt.BorderLayout.LINE_START);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTableProductsMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jTableProductsMouseClicked
    {//GEN-HEADEREND:event_jTableProductsMouseClicked
        if (evt.getClickCount() == 2)
        {
            getSelectedProduct();
        }
    }//GEN-LAST:event_jTableProductsMouseClicked

    private void jTableProductsPropertyChange(java.beans.PropertyChangeEvent evt)//GEN-FIRST:event_jTableProductsPropertyChange
    {//GEN-HEADEREND:event_jTableProductsPropertyChange

    }//GEN-LAST:event_jTableProductsPropertyChange

    private void jTableProductsKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jTableProductsKeyPressed
    {//GEN-HEADEREND:event_jTableProductsKeyPressed
        if(evt.getKeyCode() == evt.VK_ENTER)
        {
            getSelectedProduct();
        }
    }//GEN-LAST:event_jTableProductsKeyPressed

    private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt)//GEN-FIRST:event_jTabbedPane1StateChanged
    {//GEN-HEADEREND:event_jTabbedPane1StateChanged
        
    }//GEN-LAST:event_jTabbedPane1StateChanged

    private void jTableMatPrimaProductoMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jTableMatPrimaProductoMouseClicked
    {//GEN-HEADEREND:event_jTableMatPrimaProductoMouseClicked
        if(evt.getClickCount() == 2)
        {
//            int selected = jTableProductosSale.getSelectedRow();
//            DefaultTableModel productsOrder = (DefaultTableModel) jTableProductosSale.getModel();
//            Vector object = (Vector)productsOrder.getDataVector().get(selected);
//            Product product = (Product) object.get(0);
//            String amount = (String) object.get(1);
//            if(Integer.valueOf(amount)>1)
//            {
//                int newAmount = Integer.valueOf(amount) - 1;
//                object.set(1, String.valueOf(newAmount));
//                double totalPrice = (double)object.get(2);
//                double price = (product.getLatestProductPrice()!=null)?product.getLatestProductPrice().getPriceValue():0;
//                totalPrice -=price;
//                object.set(2, totalPrice);
//            }
//            else
//            {
//                productsOrder.removeRow(selected);
//            }
//
//            productsOrder.fireTableDataChanged();
//
//            if(product.getLatestProductPrice()!=null)
//            {
//                updateSubTotalSale(product.getLatestProductPrice().getPriceValue(),Constants.DELETE_OPERATION);
//            }
        }
    }//GEN-LAST:event_jTableMatPrimaProductoMouseClicked

    private void jTextFieldBuscarMatPrimaActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jTextFieldBuscarMatPrimaActionPerformed
    {//GEN-HEADEREND:event_jTextFieldBuscarMatPrimaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldBuscarMatPrimaActionPerformed

    private void jButtonBuscarMatPrimaActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonBuscarMatPrimaActionPerformed
    {//GEN-HEADEREND:event_jButtonBuscarMatPrimaActionPerformed
        //find
        findMateriaPrima();
    }//GEN-LAST:event_jButtonBuscarMatPrimaActionPerformed

    private void jButtonBuscarMatPrimaKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jButtonBuscarMatPrimaKeyPressed
    {//GEN-HEADEREND:event_jButtonBuscarMatPrimaKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButtonBuscarMatPrimaKeyPressed

    private void jListMateriaPrimaMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jListMateriaPrimaMouseClicked
    {//GEN-HEADEREND:event_jListMateriaPrimaMouseClicked
        if (evt.getClickCount() == 2)
        {

            RawMaterial material = (RawMaterial) jListMateriaPrima.getSelectedValue();
            DefaultTableModel productsRawMaterial = (DefaultTableModel) jTableMatPrimaProducto.getModel();
            
            if(material != null){
                productsRawMaterial.addRow(new Object[]{material,String.valueOf(0)});
            }
            
            productsRawMaterial.fireTableDataChanged();
            jTableMatPrimaProducto.setModel(productsRawMaterial);
            
        }
    }//GEN-LAST:event_jListMateriaPrimaMouseClicked

    private void jButtonEditMatPrimaProdActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonEditMatPrimaProdActionPerformed
    {//GEN-HEADEREND:event_jButtonEditMatPrimaProdActionPerformed
        setRawMaterialProductFieldsEditable(true);
        this.jButtonEliminarMatPrimaProd.setEnabled(false);
        this.jButtonGuardarMatPrimaProd.setEnabled(true);
    }//GEN-LAST:event_jButtonEditMatPrimaProdActionPerformed

    private void jButtonGuardarMatPrimaProdActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonGuardarMatPrimaProdActionPerformed
    {//GEN-HEADEREND:event_jButtonGuardarMatPrimaProdActionPerformed
        try {
            createOrSaveRawMatProduct();
            getAllProductsFromDB();
            this.jPanelMateriaPrimaProd.setVisible(false);            
        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        
    }//GEN-LAST:event_jButtonGuardarMatPrimaProdActionPerformed

    private void jButtonEliminarMatPrimaProdActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonEliminarMatPrimaProdActionPerformed
    {//GEN-HEADEREND:event_jButtonEliminarMatPrimaProdActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButtonEliminarMatPrimaProdActionPerformed

    private void jButtonCancelarMatPrimaProdActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonCancelarMatPrimaProdActionPerformed
    {//GEN-HEADEREND:event_jButtonCancelarMatPrimaProdActionPerformed
        this.jPanelMateriaPrimaProd.setVisible(false);
        this.jLabelDetalleProducto.setText("Seleccione un producto de la lista...");
    }//GEN-LAST:event_jButtonCancelarMatPrimaProdActionPerformed

    private void jButtonCalcularCostoActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonCalcularCostoActionPerformed
    {//GEN-HEADEREND:event_jButtonCalcularCostoActionPerformed
        try {
            this.jTextFieldCostoFinal.setText(String.valueOf(calculateProductCost()));
        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }//GEN-LAST:event_jButtonCalcularCostoActionPerformed

    private void jButtonEliminarMatPrimaProductoActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonEliminarMatPrimaProductoActionPerformed
    {//GEN-HEADEREND:event_jButtonEliminarMatPrimaProductoActionPerformed
        int selected = jTableMatPrimaProducto.getSelectedRow();
        if(selected < 0){
            JOptionPane.showMessageDialog(null, "Debe seleccionar un material a eliminar!");
        }else{
            removeProductRawMaterialFromList(selected);
        }
            
    }//GEN-LAST:event_jButtonEliminarMatPrimaProductoActionPerformed

    private void jButtonEliminarMatPrimaProductoKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jButtonEliminarMatPrimaProductoKeyPressed
    {//GEN-HEADEREND:event_jButtonEliminarMatPrimaProductoKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButtonEliminarMatPrimaProductoKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(RawMaterialProductsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RawMaterialProductsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RawMaterialProductsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RawMaterialProductsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new RawMaterialProductsUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel Center;
    private javax.swing.JPanel East;
    private javax.swing.JPanel North;
    private javax.swing.JPanel South;
    private javax.swing.JPanel West;
    private javax.swing.JButton jButtonBuscarMatPrima;
    private javax.swing.JButton jButtonCalcularCosto;
    private javax.swing.JButton jButtonCancelarMatPrimaProd;
    private javax.swing.JButton jButtonEditMatPrimaProd;
    private javax.swing.JButton jButtonEliminarMatPrimaProd;
    private javax.swing.JButton jButtonEliminarMatPrimaProducto;
    private javax.swing.JButton jButtonGuardarMatPrimaProd;
    private javax.swing.JLabel jImagenFondo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel42;
    private javax.swing.JLabel jLabelDetalleProducto;
    private javax.swing.JList jListMateriaPrima;
    private javax.swing.JPanel jPanelMateriaPrimaProd;
    private javax.swing.JPanel jPanelProducts;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JScrollPane jScrollPane7;
    private javax.swing.JScrollPane jScrollPaneProducts;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTableMatPrimaProducto;
    private javax.swing.JTable jTableProducts;
    private javax.swing.JTextField jTextFieldBuscarMatPrima;
    private javax.swing.JTextField jTextFieldCostoFinal;
    // End of variables declaration//GEN-END:variables

    private void getAllProductsFromDB()
    {
        this.jTableProducts.setModel(getProductsListModel());
        this.jTableProducts.setColumnSelectionAllowed(false);
        this.jTableProducts.getColumnModel().getColumn(0).setPreferredWidth(12);
        this.jTableProducts.getColumnModel().getColumn(2).setPreferredWidth(10);
        this.jTableProducts.getColumnModel().getColumn(3).setPreferredWidth(10);
    }

    private DefaultTableModel getProductsListModel()
    {
        List<Product> products = productManager.list();
        DefaultTableModel dm = new DefaultTableModel()
        {
            @Override
            public boolean isCellEditable(int row, int col)
            {
                return false;
            }
        };
        
        String col[] = {"Articulo","Descripcion","Costo","Precio Vta"};
        dm.setColumnIdentifiers(col);
        
        //get data from rows
        for (Product product : products) {
            double price = 0 , cost;
            if(product.getLatestProductPrice()!=null){
                price = product.getLatestProductPrice().getPriceValue();
            }
            
            cost = product.getCost();
        
            dm.addRow(new Object[]{product.getProductCode(), product.getProductDescription(), cost, price});
        
        }
        
        return dm;
    }

    private void getSelectedProduct()
    {
        int selected = this.jTableProducts.getSelectedRow();
        String productCode = (String)this.jTableProducts.getModel().getValueAt(selected, 0);
        selectedProduct = productManager.find(productCode);
        this.jLabelDetalleProducto.setText(selectedProduct.toString());
        this.jPanelMateriaPrimaProd.setVisible(true);
        this.jTextFieldBuscarMatPrima.setText("");
        
        //check if the product already has raw materials saved in DB
        List<RawMaterialProduct> rawMatProductList = rawMaterialProductManager.findByProduct(selectedProduct);
        if(rawMatProductList.isEmpty())
        {
            DefaultTableModel matPrimaProduct = getMateriaPrimaProductoModel(selectedProduct, new ArrayList<RawMaterialProduct>());
            jTableMatPrimaProducto.setModel(matPrimaProduct);
            setRawMaterialProductFieldsEditable(true);   
            this.jButtonGuardarMatPrimaProd.setEnabled(true);
            this.jButtonEditMatPrimaProd.setEnabled(false);
            this.jButtonEliminarMatPrimaProd.setEnabled(false);
        }else{
            setRawMaterialProductFieldsEditable(false);   
            this.jButtonGuardarMatPrimaProd.setEnabled(false);
            this.jButtonEditMatPrimaProd.setEnabled(true);
            this.jButtonEliminarMatPrimaProd.setEnabled(true);
            DefaultTableModel matPrimaProduct = getMateriaPrimaProductoModel(selectedProduct, rawMatProductList);
            jTableMatPrimaProducto.setModel(matPrimaProduct);
            this.jTextFieldCostoFinal.setText(String.valueOf(selectedProduct.getCost()));
        }
        
    }

    private DefaultTableModel getMateriaPrimaProductoModel(Product product, List<RawMaterialProduct> materials)
    {
        DefaultTableModel dm = new DefaultTableModel()
        {
            @Override
            public boolean isCellEditable(int row, int col)
            {
                if(col == 1){
                    return true;
                }
                return false;
            }
        };
        
        String col[] = {"Materia Prima","Cantidad"};
        dm.setColumnIdentifiers(col);
        
        //get data from rows
        if(materials.isEmpty()){
            materials = rawMaterialProductManager.findByProduct(product);
        }
        
        for (RawMaterialProduct rawMaterialProduct : materials) {
            RawMaterial material = rawMaterialProduct.getRawMaterial();
            String amount = String.valueOf(rawMaterialProduct.getAmount());
            dm.addRow(new Object[]{material,amount});        
        }
        
        return dm;
    }
    
    private void findMateriaPrima()
    {
        String matPrima = jTextFieldBuscarMatPrima.getText();
        List<RawMaterial> rawMaterials = new ArrayList<>();
        
        if(matPrima.isEmpty())
        {
            rawMaterials = rawMaterialManager.list();
        }
        else
        {
            rawMaterials = rawMaterialManager.find(matPrima);
        }
        
        DefaultListModel listModel = new DefaultListModel();
        for (RawMaterial rawMaterial : rawMaterials) 
        {
            listModel.addElement(rawMaterial);
        }
        jListMateriaPrima.setModel(listModel);
    }

    private void setRawMaterialProductFieldsEditable(boolean b)
    {
        this.jTextFieldBuscarMatPrima.setEnabled(b);
        this.jButtonBuscarMatPrima.setEnabled(b);
        this.jListMateriaPrima.setEnabled(b);
        this.jTableMatPrimaProducto.setEnabled(b);
        this.jTextFieldCostoFinal.setEnabled(b);
        this.jButtonCalcularCosto.setEnabled(b);
        
    }

    private void removeProductRawMaterialFromList(int selected)
    {
        DefaultTableModel rawMatProductModel = (DefaultTableModel) jTableMatPrimaProducto.getModel();
        rawMatProductModel.removeRow(selected);
        rawMatProductModel.fireTableDataChanged();
    }

    private void createOrSaveRawMatProduct() throws Exception
    {
        RawMaterialProduct rawMaterialProduct;
        int selected = this.jTableProducts.getSelectedRow();
        String productCode = (String)this.jTableProducts.getModel().getValueAt(selected, 0);
        selectedProduct = productManager.find(productCode);
        
        DefaultTableModel rawMaterialModel = (DefaultTableModel) this.jTableMatPrimaProducto.getModel();
        for (Iterator it = rawMaterialModel.getDataVector().iterator(); it.hasNext();) {
            Vector object = (Vector) it.next();
            RawMaterial rawMaterial = (RawMaterial) object.get(0);
            float quantity = Float.valueOf((String)object.get(1));
            rawMaterialProduct = new RawMaterialProduct(selectedProduct, rawMaterial, quantity);
            rawMaterialProductManager.saveRawMaterialProduct(rawMaterialProduct);
        }
        
        double cost = calculateProductCost();
        selectedProduct.setCost(cost);
        productManager.saveProduct(selectedProduct);
    }

    private double calculateProductCost() throws Exception
    {
        double cost = 0;
        DefaultTableModel rawMatProductsTable = (DefaultTableModel) this.jTableMatPrimaProducto.getModel();
        for (Iterator it = rawMatProductsTable.getDataVector().iterator(); it.hasNext();) {
            Vector object = (Vector) it.next();
            RawMaterial material = (RawMaterial)object.get(0);
            double amountMaterial = material.getAmount();
            double price = material.getPrice();
            double quantityUsedInProduct = Double.valueOf((String)object.get(1));
            
            if(price > 0){
                double costOfRawMaterialForProduct = (quantityUsedInProduct * price)/amountMaterial;
                cost+=costOfRawMaterialForProduct;
            }
            else{
                throw new Exception("La materia prima "+material.getName()+" no tiene precio");
            }            
        }
        
        return Math.rint(cost);
    }
}
